package com.ljc.service;

import com.ljc.auth.*;
import com.ljc.constant.AuthRoleConstant;
import com.ljc.interfaces.AuthRoleApi;
import com.ljc.interfaces.UserRoleApi;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

@Service
public class UserAuthService {
    @DubboReference
    private UserRoleApi userRoleApi;
    @DubboReference
    private AuthRoleApi authRoleApi;

    /**
     * 根据用户id获取该用户的权限
     */
    public UserAuthorities getUserAuthorities(Long userId) {
        // 获取该用户拥有的权限
        List<UserRole> userRoleList = userRoleApi.getUserRoleByUserId(userId);
        // 获取当前角色的id集合
        Set<Long> roleIdSet = userRoleList.stream().map(UserRole::getRoleId).collect(Collectors.toSet());
        // 查询操作权限列表
        // （元素操作权限）
        List<AuthRoleElementOperation> roleElementOperationList =
                authRoleApi.getRoleElementOperationsByRoleIds(roleIdSet);
        // （菜单展示权限）
        List<AuthRoleMenu> authRoleMenuList = authRoleApi.getAuthRoleMenus(roleIdSet);
        UserAuthorities userAuthorities = new UserAuthorities();
        userAuthorities.setRoleElementOperationList(roleElementOperationList);
        userAuthorities.setRoleMenuList(authRoleMenuList);
        return userAuthorities;
    }

    /**
     * 添加用户默认权限角色
     */
    public void addUserDefaultRole(Long id) {
        UserRole userRole = new UserRole();
        // 根据角色等级获得角色编号
        AuthRole role = authRoleApi.getRoleByCode(AuthRoleConstant.ROLE_LV0);
        userRole.setUserId(id);
        userRole.setRoleId(role.getId());
        // 创建用户角色
        userRoleApi.addUserRole(userRole);
    }
}
